//
//  TouzhuVC.m
//  SSC
//
//  Created by 红沙尘 on 17/6/8.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "TouzhuVC.h"
#import "TouzhuPopover.h"
#import "TouzhuCell.h"
#import "LongHuCell.h"
#import "HaomaSelectModel.h"
#import "WanfaManager.h"
#import "HaomalanVC.h"
#import "HaomalanManager.h"
#import "AppDelegate.h"

@interface TouzhuVC ()<UIPopoverPresentationControllerDelegate,TouzhuPopoverDelegate,TouzhuCellDelegate>
{
    __weak IBOutlet UILabel *hhLabel;
    __weak IBOutlet UILabel *mmLabel;
    __weak IBOutlet UILabel *ssLabel;
    
    __weak IBOutlet NSLayoutConstraint *lineA;
    __weak IBOutlet NSLayoutConstraint *footerH;
    
    __weak IBOutlet UIView *viewA;
    __weak IBOutlet UIView *viewB;
    __weak IBOutlet UIView *viewC;
    __weak IBOutlet UILabel *numLabel;
    __weak IBOutlet UIView *footerView;
    __weak IBOutlet UILabel *descLabel;
    __weak IBOutlet UIButton *xiazhuBtn;
    __weak IBOutlet UILabel *qiLabel;
    __weak IBOutlet UILabel *gouwucheLabel;
    
    __weak IBOutlet UILabel *maxLabel;
    
    CGFloat payMoney;
    
    TouzhuPopover *popVC;
    NSInteger selectIndex;
    
    WanfaManager *wanfaManager;//玩法
    HaomalanManager *haomalanManager;//号码篮
}

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation TouzhuVC

- (void)dealloc {
    NSLog(@"%s",__FUNCTION__);
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.otype = CaipiaoTypeUnknow;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    gouwucheLabel.text = [NSString stringWithFormat:@"%d",(int)[haomalanManager count]];
    gouwucheLabel.hidden = [gouwucheLabel.text intValue] == 0 ? YES : NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitle:@"投注大厅"];
    self.navigationItem.leftBarButtonItem = CUSTOMVIEW([UIView new]);
}

#pragma mark - IBAction

- (IBAction)jian
{
    int num = [numLabel.text intValue];
    
    num --;
    
    num = MAX(num, 1);
    
    [self updateBeishu:num];
}

- (IBAction)jia
{
    int num = [numLabel.text intValue];
    
    num ++;
    
    [self updateBeishu:num];
}

- (IBAction)changBeishu {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改投注倍数" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消"
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
                                                
                                                UITextField *field = alert.textFields[0];
                                                int num = [field.text intValue];
                                                [self updateBeishu:num];
                                            }]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入投注倍数";
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (IBAction)gotoHaomalan {
    
    if (haomalanManager.lanziArray.count == 0) {
        [MTool showAlertController:self message:@"号码篮里空空如也"];
        return;
    }
    
    [self.navigationController pushViewController:[[HaomalanVC alloc] initWithLanzi:haomalanManager
                                                                                 qi:qiLabel.text
                                                                              otype:self.otype]
                                         animated:YES];
}

- (IBAction)jiaruhaomalan {
    
    WanfaModel *model = [wanfaManager wanfaModelAtIndex:selectIndex];
    
    if (model.zhushu == 0) {
        
        [MTool showAlertController:self message:@"至少要1注，才能加入号码篮"];
        return;
    }
    
    WanfaModel *copyModel = [[WanfaModel alloc] initWithNamed:model.name
                                                         desc:model.desc
                                                     maxPrice:model.maxPrice];
    [copyModel updateBeishu:model.beishu];
    copyModel.playid = model.playid;
    
    [haomalanManager insertObject:copyModel];
    
    gouwucheLabel.text = [NSString stringWithFormat:@"%d",(int)[haomalanManager count]];
    gouwucheLabel.hidden = [gouwucheLabel.text intValue] == 0 ? YES : NO;
    
    for (int i = 0; i < model.dataArray.count; i ++) {
        
        HaomaSelectModel *selectModel = model.dataArray[i];
        
        HaomaSelectModel *copySselectModel = copyModel.dataArray[i];
        [copySselectModel changedType:selectModel.type];
        
        [selectModel changedType:0];
        
        NSMutableArray *array = [selectModel allHaoma];
        
        for (int j = 0; j < array.count; j ++) {
            
            HaomaModel *haomaModel = array[j];
            HaomaModel *copyHaomaModel = [copySselectModel allHaoma][j];
            copyHaomaModel.selected = haomaModel.selected;
            haomaModel.selected = NO;
        }
    }
    
    [mainTableView reloadData];
    [self updateWillPayMoney];
}

#pragma mark 下注

- (IBAction)xiazhu {
    
    if (payMoney == 0) {
        [MTool showAlertController:self message:@"至少要1注，才能下注"];
        return;
    }
    
    WeakSelf
    
    NSString *msg = [NSString stringWithFormat:@"\n确定加入：%@期\n总金额：%.2f元",qiLabel.text,payMoney];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定投注信息"
                                                                             message:msg
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDestructive
                                                      handler:^(UIAlertAction * _Nonnull action)
    {
        [weakSelf goPay];
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)goPay {

    WanfaModel *model = [wanfaManager wanfaModelAtIndex:selectIndex];

    NSMutableArray *list = @[].mutableCopy;

    NSMutableArray *array = [WanfaManager haomaWithModel:model beishu:nil];
    
    if (array.count > 0) {
        [list addObjectsFromArray:array];
    }
    
    [LoadingView show];

    [SSCRequest bettingWithAmount:[NSString stringWithFormat:@"%f",payMoney]
                            issue:qiLabel.text
                          numbers:[NSString stringWithFormat:@"%d",model.zhushu]
                            otype:self.otype
                             list:list
                          success:^(NSDictionary *responseObject) {
                              [LoadingView diss];
                              [MTool showMessage:responseObject[@"msg"] inView:nil];
                          } fail:^(NSError *error) {
                              [LoadingView diss];
                          }];
}

#pragma mark - event

- (void)updateQi:(NSString *)qi hh:(NSString *)hh mm:(NSString *)mm ss:(NSString *)ss {
    
    qi = [qi stringByReplacingOccurrencesOfString:@"第" withString:@""];
    qi = [qi stringByReplacingOccurrencesOfString:@"期" withString:@""];
    
    qiLabel.text = qi;
    
    hhLabel.text = hh;
    mmLabel.text = mm;
    ssLabel.text = ss;
}

- (void)updateWillPayMoney {
    
    NSMutableArray *selectArray = [[NSMutableArray alloc] init];
        
    WanfaModel *model = [wanfaManager wanfaModelAtIndex:selectIndex];
    
    for (HaomaSelectModel *selectModel in model.dataArray) {
        NSMutableArray *array = [selectModel allHaoma];
        
        for (HaomaModel *haomaModel in array) {
            if (haomaModel.selected) {
                [selectArray addObject:haomaModel];
            }
        }
    }
    
    payMoney = [model payMoneyWithSelectedArray:selectArray];//投注数*倍数*2元
    descLabel.text = [NSString stringWithFormat:@"已选:%d注  %d倍  %.2f元",model.zhushu,model.beishu,payMoney];
    
    footerH.constant = selectArray.count == 0 ? 0 : 65;
}

- (void)wanfashuoming {
    
    NSArray *shuomingArray = [wanfaManager wanfaShuomingArray];
    
    NSString *msg = shuomingArray[selectIndex];
    msg = [msg stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    
    UIButton *label = (UIButton *)self.navigationItem.titleView;
    NSString *title = [label titleForState:UIControlStateNormal];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[title substringToIndex:title.length - 1]
                                                                             message:msg
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showPoper:(UIButton *)button {
    
    CGSize contentSize = CGSizeMake(200, 360);
    
    popVC = [[TouzhuPopover alloc] initWithArray:[wanfaManager wanfaNamesArray] contentSize:contentSize];
    popVC.delegate = self;
    popVC.modalPresentationStyle = UIModalPresentationPopover;
    //设置依附的按钮
    popVC.popoverPresentationController.barButtonItem = CUSTOMVIEW(button);
    //可以指示小箭头颜色
    popVC.popoverPresentationController.backgroundColor = [UIColor whiteColor];
    //content尺寸
    popVC.preferredContentSize = contentSize;
    //pop方向
    popVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    //delegate
    popVC.popoverPresentationController.delegate = self;
    
    [self presentViewController:popVC animated:YES completion:nil];
}


#pragma mark UIPopoverPresentationControllerDelegate
//代理方法 ,点击即可dismiss掉每次init产生的PopViewController
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller{
    return UIModalPresentationNone;
}

#pragma mark TouzhuPopoverDelegate

- (void)touzhuTypeChanged:(NSString *)type index:(NSInteger)index{
    [popVC dismissViewControllerAnimated:YES completion:nil];
    
    selectIndex = index;
    [self titleAtIndex:index];
    
    [mainTableView reloadData];
    [self updateWillPayMoney];
}

#pragma mark TouzhuCellDelegate

- (void)touzhuCellDidSelected:(TouzhuCell *)cell {

    [mainTableView reloadData];
    [self updateWillPayMoney];
}

#pragma mark - 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [wanfaManager dataOfWanfaAtIndex:selectIndex].count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 12)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 12;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WanfaModel *wanfaModel = [wanfaManager wanfaModelAtIndex:selectIndex];
    if ([wanfaModel.name rangeOfString:@"龙虎和>万个"].length > 0) return 138;
    
    return 196;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TouzhuCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TouzhuCell"];
    
    WanfaModel *wanfaModel = [wanfaManager wanfaModelAtIndex:selectIndex];
    
    if ([wanfaModel.name rangeOfString:@"龙虎和>万个"].length > 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"LongHuCell"];
    }
    
    cell.tDelegate = self;
    
    NSMutableArray *array = [wanfaManager dataOfWanfaAtIndex:selectIndex];
    
    [cell loadWithModel:array[indexPath.section]];
    return cell;
}

#pragma mark - setup

- (void)setupData {
    footerH.constant = 0;
    wanfaManager = [[WanfaManager alloc] init];
    haomalanManager = [[HaomalanManager alloc] init];
    
    [self titleAtIndex:0];
    [self updateWillPayMoney];
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.touzhuVC = self;
    [self updateQi:app.qi hh:app.hh mm:app.mm ss:app.ss];
}

- (void)setupUI {
    hhLabel.layer.cornerRadius  = 2;
    hhLabel.layer.masksToBounds = YES;
    mmLabel.layer.cornerRadius  = 2;
    mmLabel.layer.masksToBounds = YES;
    ssLabel.layer.cornerRadius  = 2;
    ssLabel.layer.masksToBounds = YES;
    xiazhuBtn.layer.cornerRadius  = 2;
    xiazhuBtn.layer.masksToBounds = YES;
    gouwucheLabel.layer.cornerRadius  = 5;
    gouwucheLabel.layer.masksToBounds = YES;
    
    viewA.layer.borderColor = COLOR_CCCCCC.CGColor;
    viewA.layer.borderWidth = LineHeight;
    viewB.layer.borderColor = viewA.layer.borderColor;
    viewB.layer.borderWidth = viewA.layer.borderWidth;
    viewC.layer.borderColor = viewA.layer.borderColor;
    viewC.layer.borderWidth = viewA.layer.borderWidth;
    
    lineA.constant = LineHeight;

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 44)];
    btn.titleLabel.font = [MTool fontOfSize:14];
    [btn setTitle:@"玩法说明" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(wanfashuoming) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = CUSTOMVIEW(btn);

    [mainTableView registerNib:[UINib nibWithNibName:@"TouzhuCell" bundle:nil]
        forCellReuseIdentifier:@"TouzhuCell"];
    [mainTableView registerNib:[UINib nibWithNibName:@"LongHuCell" bundle:nil]
        forCellReuseIdentifier:@"LongHuCell"];
    
}

- (void)titleAtIndex:(NSInteger)index {
    
    selectIndex = index;
    
    WanfaModel *model = [wanfaManager wanfaModelAtIndex:selectIndex];
    numLabel.text = [NSString stringWithFormat:@"%d",model.beishu];
    maxLabel.text = model.maxPrice;
    
    UIButton *titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [titleBtn setTitle:[wanfaManager wanfaNamesArray][index] forState:UIControlStateNormal];
    [titleBtn addTarget:self action:@selector(showPoper:) forControlEvents:UIControlEventTouchUpInside];
    titleBtn.titleLabel.font = [MTool fontOfSize:16];
    self.navigationItem.titleView = titleBtn;
}

- (void)updateBeishu:(int)num {
    numLabel.text = [NSString stringWithFormat:@"%d",num];
    
    WanfaModel *model = [wanfaManager wanfaModelAtIndex:selectIndex];
    [model updateBeishu:num];
    
    [self updateWillPayMoney];
}

@end
